package com.ljc.aop;

import com.ljc.auth.UserRole;
import com.ljc.constant.AuthRoleConstant;
import com.ljc.entity.UserMoment;
import com.ljc.exception.ConditionException;
import com.ljc.interfaces.UserRoleApi;
import com.ljc.support.UserSupport;
import org.apache.dubbo.config.annotation.DubboReference;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Order(1)
@Component
@Aspect
public class DataLimitedAspect {
    @Resource
    private UserSupport userSupport;
    @DubboReference
    private UserRoleApi userRoleApi;

    @Pointcut("@annotation(com.ljc.annotation.DataLimited)")
    public void check() {
    }

    /**
     * 校验用户是否有权限
     */
    @Before("check()")
    public void doBefore(JoinPoint joinPoint) {
        Long userId = userSupport.getCurrentUserId();
        List<UserRole> userRoleList = userRoleApi.getUserRoleByUserId(userId);
        Set<String> roleCodeSet = userRoleList.stream().map(UserRole::getRoleCode).collect(Collectors.toSet());
        // 获取当前切入方法的参数
        for (Object arg : joinPoint.getArgs()) {
            // 判断传入参数类型是否是用户动态
            if (arg instanceof UserMoment) {
                UserMoment userMoment = (UserMoment) arg;
                String type = userMoment.getType();
                // 如果当前角色存在LV0参数，但是用户动态的类型不是0，即视频的话，就抛出异常
                // （等级为LV0的用户只能发视频）
                if (roleCodeSet.contains(AuthRoleConstant.ROLE_LV0) && !"0".equals(type)) {
                    throw new ConditionException("参数异常");
                }
            }
        }
    }
}
